<?php

namespace app\api\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\product\Sku;
use app\admin\model\total\Bill;
use app\admin\model\user\Finance;
use app\common\controller\Bonus;
use think\Db;
use think\Request;
use app\common\controller\Api;

class Productorder extends Api
{
    protected static $model = null;
    protected $noNeedRight = '*';
    protected static $totalList = 15;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Order();
    }

    /**
     * 提交订单
     */
    public function createorder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }
        $user_id = $this->auth->id;
        $finance = Finance::where('user_id', $user_id)->find();
        $is_trans = input('is_trans', 1); //是否需要物流
        $tag = input('tag');
        $message = input('message');
        if (!$tag) {
            $this->error('非法操作！');
        }

//        $password = input('password');
//        if ($uinfo['psd2'] != $password) {
//            $this->apiError('支付密码错误！');
//        }

        $orderInfo = Order::where('orderid', $tag)->find();
        if ($orderInfo) {
            $this->error('重复提交订单');
        }

        $addressid = 0;
        if ($is_trans) {
            $addressid = \app\admin\model\Transport::where("status='1' and user_id='$user_id'")->value('id');
            if ($addressid <= 0) {
                $this->error('必须默认一个收货地址！');
            }
        }

        //获取该用户购物清单中的数据
        $shoplist = Listo::where('tag', $tag)->select();

        if (!$shoplist) {
            $this->error('请先购买商品！');
        }

        $nums = 0;
        $total = 0;
        $transfee = 0;
        $mark = '';
        foreach ($shoplist as $v) {
            $productInfo = Lists::where('id', $v->product_id)->find();
            $cmark = Category::where('id', $productInfo->category_id)->value('mark');

            if ($mark == '') {
                $mark = $cmark;
            } else {
                if ($cmark != $mark) {
                    $this->error('一次只能购买一个种类的商品！');
                }
            }

            if ($cmark == 'bill' && $finance->hasscore > 0) {
                $this->error('积分余额尚未耗尽，不可购买报单产品！');
            }

            $nums += $v['num'];
            $total += $v['total'];
            if ($is_trans == 1) {
                $transfee += $productInfo['transfee'] * $v['num'];
            }
        }

        $all = $total + $transfee;
        if ($mark == 'bill') {
            // 报单
            if ($all > $finance->hasbill) {
                $this->error('账户报单积分余额不足，无法购买！');
            }
            $paytype = 1;
        } else {
            // 复消
            if ($all > $finance->hasshop) {
                $this->error('账户商城钱包余额不足，无法购买！');
            }
            $paytype = 6;
        }

        $data['addressid'] = $addressid;//收货人地址
        $data['total'] = $total;//总金额
        $data['transfee'] = $transfee;
        $data['all'] = $all;
        $data['orderid'] = $tag;//订单号
        $data['user_id'] = $user_id;//当前用户id
        $data['backinfo'] = '预下单';
        $data['message'] = $message;
        $data['paytype'] = $paytype;//等待发货
        $data['mark'] = $mark;
        $data['is_trans'] = $is_trans;
        $data['status'] = 0;

        Db::startTrans();
        try {
            $odata = self::$model->create($data);
            Listo::where('tag', $tag)->setField('order_id', $odata->id);
            if ($mark == 'bill') {
                // 报单
                $finance->hasbill -= $all;
            } else {
                // 复消
                $finance->hasshop -= $all;
            }

            $finance->save();

            if ($mark == 'bill') {
                $today = date('Y-m-d', strtotime('today'));
                $today_bill = Bill::where('time', $today)->value('total');
                if (!$today_bill) {
                    $today_bill = config('site.total_bill');
                }

                /*更新状态*/
                $ndata = [
                    'pay_time' => time(),
                    'status' => 1
                ];
                $today_total = $odata->total;

                if ($today_total + $total > $today_bill) {
                    $ndata['status'] = 5;
                } else {
                    $bonus = new Bonus($user_id, $total);
                    $bonus->giveMoney($nums);
                    $bonus->bonusRecom();
                    $bonus->bonusLevel();
                    $bonus->bonusHouse();
                    $bonus->bonusOperat();
                    \app\admin\model\User::where('id', $user_id)->setField('rank', 1);
                    $bonus->addAchievement();
                    $bonus->bonusUpdate();
                }

                Listo::where('order_id', $odata->id)->update($ndata);
                $ndata['backinfo'] = '已下单';
                $odata->save($ndata);

                self::updateShop($odata->id);
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $orderNum = create_order($user_id);
        $mdata = [
            'order_num' => $orderNum,
            'record_type' => 0,
            'change_type' => 30,
            'money' => $all,
            'remark' => $tag,
            'user_id' => 0,
            'targetuserid' => $user_id
        ];
        if ($mark == 'bill') {
            $mdata['moneytype'] = 1;
            $mdata['hasmoney'] = $finance->hasbill;
        } else {
            $mdata['moneytype'] = 4;
            $mdata['hasmoney'] = $finance->hasshop;
        }
        Change::create($mdata);

        $this->success("订单提交成功！");

    }

    /**
     * 更新商品销量
     * @param $list
     * @throws \think\Exception
     */
    private function updateShop($orderId)
    {
        $list = Listo::where('order_id', $orderId)->select();
        foreach ($list as $k => $val) {
            Sku::where('id', $val->sku_id)->setDec('stock', $val['num']);
            Lists::where(array('id' => $val->product_id))->setInc('sell_num', $val['num']);
            Lists::where(array('id' => $val->product_id))->setDec('goods_num', $val['num']);
        }
    }

    /**
     * 订单列表
     */
    public function lists()
    {
        $pageSize = input('page_size', self::$totalList);
        $status = input('status', -1);
        $mark = input('type', '');
        $user_id = $this->auth->id;
        if ($status > -1) {
            $map['status'] = $status;
        } else {
            $map['status'] = ['>=', 0];
        }

        if ($mark) {
            $map['mark'] = $mark;
        } else {
            $map['status'] = ['>=', 0];
        }
        $orders = self::$model
            ->field("id,orderid,is_trans,total,transfee,all,status,paytype,addressid,createtime")
            ->where('user_id', $user_id)
            ->where($map)
            ->order('id desc')
            ->paginate($pageSize)
            ->each(function ($item) {
                $lists = Listo::where('order_id', $item['id'])->select();
                $totalNum = 0;
                if (count($lists) > 0) {
                    foreach ($lists as &$vv) {
                        $pInfo = Lists::where('id', $vv['product_id'])->find();
//                        $vv['product_name'] = $pInfo['product_name'];
//                        $vv['parameter'] = ProductSku::where('id', $vv['parameter_id'])->value('value');

                        $attrs = $this->get_attrs($pInfo['intro']);
                        $vv['attrs'] = $attrs;
                        $vv['intro'] = $pInfo['intro'];
                        $vv['image'] = make_full_url($pInfo['image']);
                        $totalNum += $vv['num'];
                    }
                }
                $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
                $item['total_num'] = $totalNum;
                $item['product_list'] = $lists;
            });

        $totalCount = self::$model
            ->where('user_id', $user_id)
            ->where($map)
            ->count();

        $this->success('订单列表', ['list' => $orders, 'totalCount' => $totalCount]);
    }

    /**
     * 确认订单
     */
    public function confirmOrder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }

        $id = input('id');
        $list = Listo::where('id', $id)->find();

        if (!$list) {
            $this->error('该订单不存在！');
        }

        $order = self::$model->find($list['order_id']);
        if ($order->is_trans == 1) {
            if ($list['status'] != 10) {
                $this->error('该订单不可确认！');
            }
        } else {
            if ($list['status'] != 1) {
                $this->error('该订单不可确认！');
            }
        }

        $time = time();
        $list->status = 20;
        $list->finish_time = $time;
        $res = $list->save();
        if ($res) {
            $num = Listo::where('order_id', $list['order_id'])->where('status', 'lt', 20)->count();
            if ($num == 0) {
                $data = [
                    'finish_time' => $time,
                    'status' => 20
                ];
                $order->save($data);
            }
            $this->success('签单成功');
        }
    }

    /**
     * 删除订单
     */
    public function delOrder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }

        $id = input('id');
        $orderInfo = self::$model->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('该订单不存在！');
        }
        if ($orderInfo['status'] != 20) {
            $this->error('该订单不可删除！');
        }

        $res = self::$model->where('id', $id)->update(['status' => -2]);
        if (!$res) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }
}